package ru.kruzhki.client.ui.addcompany;

import ru.kruzhki.client.place.NameTokens;
import ru.kruzhki.client.ui.main.MainPagePresenter;
import ru.kruzhki.shared.command.AddCompanyRequest;
import ru.kruzhki.shared.command.AddCompanyResponse;
import ru.kruzhki.shared.model.Company;

import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.inject.Inject;
import com.google.web.bindery.event.shared.EventBus;
import com.gwtplatform.dispatch.shared.DispatchAsync;
import com.gwtplatform.mvp.client.Presenter;
import com.gwtplatform.mvp.client.View;
import com.gwtplatform.mvp.client.annotations.NameToken;
import com.gwtplatform.mvp.client.annotations.ProxyCodeSplit;
import com.gwtplatform.mvp.client.proxy.ProxyPlace;
import com.gwtplatform.mvp.client.proxy.RevealContentEvent;
import com.sencha.gxt.widget.core.client.box.MessageBox;

public class AddCompanyPresenter extends Presenter<AddCompanyPresenter.MyView, AddCompanyPresenter.MyProxy> {
    public interface MyViewHandler {
        void onAddCompany(Company company);
    }
    
    public interface MyView extends View {
        void setViewHandler(MyViewHandler viewHandler);
    }

	@ProxyCodeSplit
	@NameToken(NameTokens.ADD_COMPANY)
	public interface MyProxy extends ProxyPlace<AddCompanyPresenter> {
		//gwtp boilerplate
	}


	private final DispatchAsync dispatcher;



	@Inject
	public AddCompanyPresenter(final EventBus eventBus, final MyView view,
			final MyProxy proxy, final DispatchAsync dispatcher) {
		super(eventBus, view, proxy);

		this.dispatcher = dispatcher;
	}

	@Override
	protected void revealInParent() {
		RevealContentEvent.fire(this, MainPagePresenter.TYPE_content, this);
	}


	@Override
	protected void onBind() {
		super.onBind();
		getView().setViewHandler(new MyViewHandler() {
            
            @Override
            public void onAddCompany(Company company) {
            	dispatcher.execute(new AddCompanyRequest(company), new AsyncCallback<AddCompanyResponse>() {

					@Override
					public void onFailure(Throwable caught) {
						new MessageBox("Ошибка",String.valueOf(caught)).show();
					}

					@Override
					public void onSuccess(AddCompanyResponse result) {
						new MessageBox("result",String.valueOf(result.getId())).show();
					}
				});
            }
        });
	}

	@Override
	protected void onReset() {
		super.onReset();
	}
}
